package com.tys.algorithm.advanced.code.class01;

import java.util.Arrays;

/**
 * 二分查找：数是否存在
 */
public class Code04_BSExist {

    public static boolean exist(int[] arr, int num) {
        if (arr == null || arr.length == 0) {
            return false;
        }
        int L = 0; //左边界
        int R = arr.length - 1; //右边界
        int mid = 0; //中间位置
        // [L, R - 1]
        while (L < R) { // L..R 至少两个数的时候
            //二分使用位运算避免溢出越界
            mid = L + ((R - L) >> 1);
            if (arr[mid] == num) { //找到了
                return true;
            } else if (arr[mid] > num) { // 中值大了在左边找，R向左移动
                R = mid - 1;
            } else { //中值小了在右边找，L向右移动
                L = mid + 1;
            }
        }
        //最后比较L==R时位置的数
        return arr[L] == num;
    }

    // for test
    public static boolean test(int[] sortedArr, int num) {
        for (int cur : sortedArr) {
            if (cur == num) {
                return true;
            }
        }
        return false;
    }


    // for test
    public static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
        }
        return arr;
    }

    public static void printArray(int[] arr) {
        if (arr == null) {
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 10;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr = generateRandomArray(maxSize, maxValue);
            Arrays.sort(arr);
            int value = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
            if (test(arr, value) != exist(arr, value)) {
                succeed = false;
                break;
            }
        }
        System.out.println(succeed ? "Nice!" : "Fucking fucked!");
    }

}
